#pragma once

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include "Log.hpp"
#include "lockGuard.hpp"

const static int g_backlog = 20;

class TcpServer
{
private:
    uint16_t _port;
    int _listenSocket;
    static TcpServer *tcpSvr;
    static pthread_mutex_t mutex;

private:
    TcpServer(uint16_t port)
        : _port(port),
          _listenSocket(-1)
    {
    }

    TcpServer(const TcpServer &s) = delete;
    TcpServer &operator=(const TcpServer &s) = delete;

public:
    static TcpServer *getTcpSvrInstance(int _port)
    {
        if (nullptr == tcpSvr)
        {
            lockGuard lockguard(&mutex);
            if (nullptr == tcpSvr)
            {
                tcpSvr = new TcpServer(_port);
                tcpSvr->InitServer();
            }
        }
        return tcpSvr;
    }

    void InitServer()
    {
        Socket();
        Bind();
        Listen();
        LOG(INFO, "tcp_server init success");
    }

    void Socket()
    {
        _listenSocket = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenSocket < 0)
        {
            LOG(FATAL, "socket error!");
            exit(1);
        }
        int opt = 1;
        setsockopt(_listenSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        LOG(INFO, "create socket %d success", _listenSocket);
    }

    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // 云服务器不能直接绑定公网IP

        if (bind(_listenSocket, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error!");
            exit(2);
        }
        LOG(INFO, "bind socket %d success", _listenSocket);
    }

    void Listen()
    {
        if (listen(_listenSocket, g_backlog) < 0)
        {
            LOG(FATAL, "listen socket error!");
            exit(3);
        }
        LOG(INFO, "listen socket %d success", _listenSocket);
    }

    int getListenSock()
    {
        return _listenSocket;
    }

    ~TcpServer()
    {
        if (_listenSocket >= 0)
            close(_listenSocket);
    }
};

TcpServer *TcpServer::tcpSvr = nullptr;
pthread_mutex_t TcpServer::mutex = PTHREAD_MUTEX_INITIALIZER;